package org.hot100.h160;

/**
 * @Author: wjy
 * @Date: 2022/1/6 17:02
 */
public class Solution {

    /**
     * 给你两个单链表的头节点 headA 和 headB ，请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点，返回 null 。
     *
     * @param args
     */
    public static void main(String[] args) {

        ListNode c1 = new ListNode(6);
        ListNode c2 = new ListNode(7);
        ListNode c3 = new ListNode(8);
        c1.next = c2;
        c2.next = c3;
        ListNode a1 = new ListNode(1);
        ListNode a2 = new ListNode(2);
        a1.next = a2;
        a2.next = c1;
        ListNode b1 = new ListNode(3);
        ListNode b2 = new ListNode(4);
        ListNode b3 = new ListNode(5);
        b1.next = b2;
        b2.next = b3;
        b3.next = c1;

        Solution solution = new Solution();
        System.out.println(solution.getIntersectionNode(a1, b1).val);

    }

    /**
     * 绝！！！
     *
     * @param headA
     * @param headB
     * @return
     */
    public ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
        ListNode A = headA, B = headB;
        while (A != B) {
            A = A != null ? A.next : headB;
            B = B != null ? B.next : headA;
        }
        return A;
    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {

        ListNode tempA = headA, tempB = headB;

        while (true) {
            if (tempA == null && tempB == null) {
                break;
            }
            if (tempA == null) {
                tempA = headB;
            }
            if (tempB == null) {
                tempB = headA;
            }
            if (tempA == tempB) {
                return tempA;
            }

            tempA = tempA.next;
            tempB = tempB.next;
        }
        return null;

    }

}

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
        next = null;
    }
}
